// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../../../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 是否使用窗口
const useWindow = true;
// ✅ 窗口大小
const windowSize = 5;

// ✅ 存储预测结果
const predictResults = [];
let correct = 0;
let maxWrongStreak = 0;
let currentWrongStreak = 0;

/**
 * 获取斐波那契序列中不超过 max 的数字集合
 * 例如：max = 49 -> [1, 2, 3, 5, 8, 13, 21, 34]
 */
function getFibonacciPositions(max) {
  const fib = [1, 2];
  while (true) {
    const next = fib[fib.length - 1] + fib[fib.length - 2];
    if (next > max) break;
    fib.push(next);
  }
  return fib;
}

/**
 * 斐波那契分布策略
 * - 计算窗口中每个号码的出现次数
 * - 按照频率排序后，从斐波那契位置挑选高频号码
 */
function select32ByFibonacci(temp) {
  const freqMap = {};

  temp.forEach((item) => {
    const num = item.number;
    freqMap[num] = (freqMap[num] || 0) + 1;
  });

  // 所有号码按频率降序排列
  const sorted = allNumbers
    .map((num) => ({
      number: num,
      count: freqMap[num] || 0,
    }))
    .sort((a, b) => b.count - a.count || a.number.localeCompare(b.number));

  // 获取斐波那契下标位置
  const fibPositions = getFibonacciPositions(sorted.length); // e.g. [1, 2, 3, 5, 8, 13, 21, 34]
  const selectedSet = new Set();

  fibPositions.forEach((pos) => {
    if (pos - 1 < sorted.length) {
      selectedSet.add(sorted[pos - 1].number);
    }
  });

  // 若不足 32 个，再从前面补充
  for (let i = 0; i < sorted.length && selectedSet.size < 32; i++) {
    selectedSet.add(sorted[i].number);
  }

  const selected = Array.from(selectedSet);
  if (selected.length !== 32) {
    throw new Error(`❗ 选出号码不足 32 个（实际 ${selected.length}）`);
  }

  return selected;
}

// ✅ 主循环
allValues.forEach((item, index) => {
  const temp = useWindow
    ? allValues.slice(Math.max(0, index - windowSize), index)
    : allValues.slice(0, index);

  if (!temp.length) return;

  const selectedNumbers = select32ByFibonacci(temp);

  if (selectedNumbers.length !== 32) {
    throw new Error("选出的32个号码数量不正确");
  }

  try {
    const isHit = checkAccuracy(selectedNumbers, item.number);
    if (isHit) {
      correct += 1;
      currentWrongStreak = 0;
    } else {
      currentWrongStreak += 1;
      maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
    }
    predictResults.push(selectedNumbers);
  } catch (err) {
    console.error(`❌ checkAccuracy error at index ${index}: ${err.message}`);
  }
});

// ✅ 输出统计结果
const total = predictResults.length;
const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);
